
//
//  XMGTopWindow.m
//  百思不得姐
//
//  Created by Mine on 16/8/19.
//  Copyright © 2016年 Min. All rights reserved.

/**
 1.定义静态的window_，并且设置level和添加tao Gesture
 2.注意:这个方法里面全是类方法
 3.遍历keyWindow里的scrollView,判断滑动到顶部的时候。
 4.使用方法  isShowingOnKeyWindow
 */

#import "XMGTopWindow.h"



@implementation XMGTopWindow

static UIWindow * window_;
+ (void)initialize
{
    window_ = [[UIWindow alloc]init];
    window_.frame = CGRectMake(0, 0, XMGScreenW, 20);
    window_.windowLevel = UIWindowLevelAlert;
    
    [window_ addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(windowClick)]];
}

+ (void)show
{
     window_.hidden = NO;
}

+ (void)hide
{
    window_.hidden = YES;
}

/**
    监听窗口点击
 */
+ (void)windowClick
{
    // 获取keyWindow
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    
    [self searchScrollViewInView:window];
}

// 在根控制器里面，设置UIScrollView；判断是否滚动到最顶部
+ (void)searchScrollViewInView:(UIView *)superview
{
    for (UIScrollView *subview in superview.subviews) {
        
        //        CGRectIntersectsRect([UIApplication sharedApplication].keyWindow.bounds, subview.frame)
        
        //        CGRect newFrame = [subview.superview convertRect:subview.frame toView:nil];
        //        CGRect newFrame = [[UIApplication sharedApplication].keyWindow convertRect:subview.frame fromView:subview.superview];
        
        // 如果是scrollview, 滚动最顶部
        if ([subview isKindOfClass:[UIScrollView class]] && subview.isShowingOnKeyWindow) {
            CGPoint offset = subview.contentOffset;
            offset.y = - subview.contentInset.top;
            [subview setContentOffset:offset animated:YES]; // 设置动画
        }
        
        // 继续查找子控件
        [self searchScrollViewInView:subview];
    }

}
@end
